<template>
    <UploadExcel :downloadTemplate="getExcelTemplate" :onSuccess="success"></UploadExcel>
</template>

<script>
import { addEmployeeBatch, getExcelTemplate } from '@/api/employees'
import FileSaver from 'file-saver';
export default {
    name: 'ImportIndex',
    methods: {
        async getExcelTemplate() {
            const blob = await getExcelTemplate()
            FileSaver.saveAs(blob, '员工导入模板.xlsx')
        },
        async success(data) {
            const { results } = data
            // 定义中文名/英文名对应关系
            const userRelation = {
                '姓名': 'username',
                '手机号': 'mobile',
                '入职日期': 'timeOfEntry',
                '转正日期': 'correctionTime',
                '工号': 'workNumber',
                '部门': 'departmentName',
                '聘用形式': 'formOfEmployment'
            }
            const newResults = []
            results.forEach(item => {
                // 每一个item就是一条user对象
                const user = {}
                Object.keys(item).forEach(key => {
                    // excel插件处理的日期格式不对，我们这里手动处理，首先判断是否为日期类型
                    if(userRelation[key] === 'timeOfEntry' || userRelation[key] === 'correctionTime') {
                        // 将日期转为 yyyy/mm/dd 形式并用 new Date()处理 再赋值
                        user[userRelation[key]] = new Date( this.formatDate(item[key], '/') )
                    } else {
                        user[userRelation[key]] = item[key]
                    }
                })
                newResults.push(user)
            })
            // 调用批量导入接口
            await addEmployeeBatch(newResults)
            this.$message.success('批量导入成功')
            this.$router.back()
        },
        // 由于经excel插件处理，内容有时间格式的会转化不正确
        formatDate(numb, format) {
            const time = new Date((numb - 1) * 24 * 3600000 + 1)
            time.setYear(time.getFullYear() - 70)
            const year = time.getFullYear() + ''
            const month = time.getMonth() + 1 + ''
            const date = time.getDate() + ''
            if (format && format.length === 1) {
                return year + format + month + format + date
            }
            return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
        }
    }
}
</script>

<style></style>